package cn.iocoder.yudao.module.member.user.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.qrcode.pojo.QrCodeInviteType;
import cn.iocoder.yudao.framework.qrcode.util.QrCodeUtils;
import cn.iocoder.yudao.framework.region.RegionUtils;
import cn.iocoder.yudao.framework.region.enums.RegionDataSet;
import cn.iocoder.yudao.module.api.infrastructure.dept.DeptApi;
import cn.iocoder.yudao.module.api.infrastructure.dept.PostApi;
import cn.iocoder.yudao.module.api.infrastructure.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.dept.dto.PostRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.file.FileApi;
import cn.iocoder.yudao.module.api.infrastructure.social.SocialUserApi;
import cn.iocoder.yudao.module.api.infrastructure.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.social.enums.SocialTypeEnum;
import cn.iocoder.yudao.module.member.user.dal.dataobject.MemberUserDO;
import cn.iocoder.yudao.module.member.user.service.MemberUserService;
import cn.iocoder.yudao.module.member.user.service.SecurityMemberService;
import cn.iocoder.yudao.module.member.user.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 个人中心")
@RestController
@RequestMapping("/member/user")
@Validated
@Slf4j
public class AppMemberUserController {

    @Resource
    private MemberUserService memberUserService;
    @Resource
    private SecurityMemberService securityMemberService;

    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private PostApi postApi;
    @Resource
    private FileApi fileApi;

    @GetMapping("/get")
    @Operation(summary = "获得自己的基本信息", description = "完整的用户信息请使用`/member/user/getV2`代替")
    @PermitAll
    public CommonResult<UserSimpleVO> getUserInfo() {
        Long userId = getLoginUserId();
        if (userId == null || userId < 0) {
            return success(null);
        }
        UserSimpleVO user = memberUserService.getUserFromCache(userId);
        return success(user);
    }

    @GetMapping("/getV2")
    @Operation(summary = "获得自己的详细信息", description = "避免前端在未登录的情况下调用报 403 从而强制跳转登录页")
    @PermitAll
    public CommonResult<AppMemberUserInfoRespVO> getUserInfoV2() {
        Long userId = getLoginUserId();
        if (userId == null || userId < 0) {
            return success(null);
        }
        MemberUserDO user = memberUserService.getUser(userId);
        AppMemberUserInfoRespVO respVO = toRespVO(user);
        return success(respVO);
    }

    @GetMapping("/get-simple")
    @Operation(summary = "获得别人的信息（按用户编号）")
    @Parameter(name = "userId", description = "用户编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<UserSimpleVO> getUserInfoSimple(@RequestParam("userId") Long userId) {
        UserSimpleVO user = memberUserService.getUserFromCache(userId);
        return success(user);
    }

    @GetMapping("/get-simple-by-no")
    @Operation(summary = "获得别人的信息（按用户身份码）")
    @Parameter(name = "no", description = "用户身份码", required = true, example = "TEST000001")
    @PermitAll
    public CommonResult<UserSimpleVO> getUserInfoSimple(@RequestParam("no") String no) {
        MemberUserDO user = memberUserService.getUserByNo(no);
        return success(BeanUtils.toBean(user, UserSimpleVO.class));
    }


    @PostMapping("/update")
    @Operation(summary = "修改基本信息")
    public CommonResult<Boolean> updateUser(@RequestBody @Valid AppMemberUserUpdateReqVO reqVO) {
        memberUserService.updateUser(getLoginUserId(), reqVO);
        return success(true);
    }

    @PostMapping("/update-avatar")
    @Operation(summary = "修改头像")
    public CommonResult<Boolean> updateUserAvatar(@RequestBody @Valid AppMemberUserAvatarUpdateReqVO reqVO) {
        memberUserService.updateUserAvatar(getLoginUserId(), reqVO.getAvatar());
        return success(true);
    }

    @PostMapping("/update-nickname")
    @Operation(summary = "修改昵称")
    public CommonResult<Boolean> updateUserNickname(@RequestBody @Valid AppMemberUserNicknameUpdateReqVO reqVO) {
        memberUserService.updateUserNickname(getLoginUserId(), reqVO.getNickname());
        return success(true);
    }

    @PostMapping("/update-dept-post")
    @Operation(summary = "修改部门及岗位")
    public CommonResult<Boolean> updateUserDeptAndPost(@RequestBody @Valid AppMemberUserDeptAndPostUpdateReqVO reqVO) {
        memberUserService.updateDeptAndPost(getLoginUserId(), reqVO.getDeptId(), reqVO.getPostIds());
        return success(true);
    }

    @PostMapping("/update-region")
    @Operation(summary = "修改行政区域")
    public CommonResult<Boolean> updateUserRegion(@RequestBody @Valid AppMemberUserUpdateRegionReqVO reqVO) {
        memberUserService.updateUserRegion(getLoginUserId(), reqVO);
        return success(true);
    }

    @PostMapping("/update-mobile")
    @Operation(summary = "修改手机号（基于短信验证码）")
    public CommonResult<Boolean> updateUserMobile(@RequestBody @Valid AppMemberUserUpdateMobileReqVO reqVO) {
        memberUserService.updateUserMobile(getLoginUserId(), reqVO);
        return success(true);
    }

    @PostMapping("/update-mobile-by-weixin")
    @Operation(summary = "修改手机号（基于微信小程序的授权码）")
    public CommonResult<Boolean> updateUserMobileByWeixin(@RequestBody @Valid AppMemberUserUpdateMobileByWeixinReqVO reqVO) {
        memberUserService.updateUserMobileByWeixin(getLoginUserId(), reqVO);
        return success(true);
    }

    @PostMapping("/update-password")
    @Operation(summary = "修改密码（基于短信验证码）", description = "用户修改密码时使用")
    public CommonResult<Boolean> updateUserPassword(@RequestBody @Valid AppMemberUserUpdatePasswordReqVO reqVO) {
        memberUserService.updateUserPassword(getLoginUserId(), reqVO);
        return success(true);
    }

    @PostMapping("/reset-password")
    @Operation(summary = "重置密码（基于短信验证码）", description = "用户忘记密码时使用")
    @PermitAll
    public CommonResult<Boolean> resetUserPassword(@RequestBody @Valid AppMemberUserResetPasswordReqVO reqVO) {
        memberUserService.resetUserPassword(reqVO);
        return success(true);
    }

    @PostMapping("/cancellation")
    @Operation(summary = "注销", description = "需谨慎操作，将删除用户及用户关联的账号（如第三方社交账号、后台管理账号）")
    public CommonResult<Boolean> cancellation() {
        memberUserService.cancellation(getLoginUserId());
        return success(true);
    }

    private AppMemberUserInfoRespVO toRespVO(MemberUserDO user) {
        if (user == null) {
            return null;
        }
        AppMemberUserInfoRespVO respVO = BeanUtils.toBean(user, AppMemberUserInfoRespVO.class);
        respVO.setIsVip(securityMemberService.isVipMember());
        boolean isVipMerchant = securityMemberService.isVipMerchant();
        if (isVipMerchant) {
            respVO.setIsVip(true);
        }
        respVO.setIsMerchant(securityMemberService.isMerchant());
        respVO.setIsMerchantVip(isVipMerchant);
        respVO.setIsAgency(securityMemberService.isAgency());
        respVO.setIsCloudAlliance(securityMemberService.isCloudAlliance());
        respVO.setIsSupplier(false); //TODO 待实现
        respVO.setIsWholesaler(false); //TODO 待实现
        respVO.setIsVerifier(securityMemberService.isVerifier());
        respVO.setIsRider(securityMemberService.isRider());
        respVO.setIsCashier(securityMemberService.isCashier());
        respVO.setIsRecruiter(false); //TODO 待实现
        if (user.getDeptId() != null && user.getDeptId() > 0) {
            DeptRespDTO dept = deptApi.getDept(user.getDeptId());
            respVO.setDeptName(dept.getName());
        } else {
            respVO.setDeptName("未知");
        }
        if (CollUtil.isNotEmpty(user.getPostIds())) {
            List<String> postNames = postApi.getPostList(user.getPostIds()).stream().map(PostRespDTO::getName).toList();
            respVO.setPostNames(postNames);
        } else {
            respVO.setPostNames(Collections.emptyList());
        }
        String countyCode = RegionUtils.convertRegionIdToCode(user.getAreaId());
        RegionUtils.autoAssignCounty(RegionDataSet.ONLY_LATEST, countyCode, respVO);
        SocialUserRespDTO socialUserRespDTO = socialUserApi.getSocialUserByUserId(UserTypeEnum.MEMBER.getValue(), user.getId(), SocialTypeEnum.WECHAT_MINI_PROGRAM.getType());
        if (socialUserRespDTO != null) {
            respVO.setWxOpenId(socialUserRespDTO.getOpenid());
        }
        QrCodeInviteType type = new QrCodeInviteType();
        type.setMemberNo(user.getNo());
        String fileName = "member_no_" + user.getNo() + ".png";
        String path = "qrcode/" + fileName;
        String url = fileApi.getUrlByPath(path);
        if (StrUtil.isBlank(url)) {
            url = fileApi.createFile(fileName, path, QrCodeUtils.generatePng(type, user.getAvatar()));
        }
        respVO.setQrcode(url);
        return respVO;
    }

}